package cn.itsource.ymcc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration//标识配置类
@EnableWebSecurity//启动配置
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled= true)//开启注解权限的支持
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    //密码编码器：不加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //配置认证管理器，授权模式为“poassword”时会用到
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry = http.formLogin()                              //允许表单登录
                .successForwardUrl("/loginSuccess")             // 设置登陆成功页  必须是post
                .and().authorizeRequests()                                //授权配置
                .antMatchers("/login", "/hello","/login/accountLogin").permitAll();

//        expressionInterceptUrlRegistry  //登录路径放行
//                .antMatchers("/course/pagelist").hasAuthority("course:pagelist");

        expressionInterceptUrlRegistry//需要什么权限 403就是没有权限
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
            .and().logout().permitAll()                    //登出路径放行 /logout
            .and().csrf().disable();                        //关闭跨域伪造检查  可以提供效率
    }
}
